import json
import pyecharts
from pyecharts.charts import Line  # 折线图
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts, LabelOpts, ItemStyleOpts, LineStyleOpts

# 读取数据
f_us = open("美国.txt", 'r', encoding='UTF-8')
f_jp = open("日本.txt", 'r', encoding='UTF-8')
f_ind = open("印度.txt", 'r', encoding='UTF-8')

# 删去不合适的格式，匹配出json格式，得到可用的json字符串
str_us = f_us.read()
str_us = str_us.replace("jsonp_1629344292311_69436(", "")  # 开头替换
str_us = str_us[:-2]  # 结尾去除
str_jp = f_jp.read()
str_jp = str_jp.replace("jsonp_1629350871167_29498(", "")  # 开头替换
str_jp = str_jp[:-2]  # 结尾去除
str_ind = f_ind.read()
str_ind = str_ind.replace("jsonp_1629350745930_63180(", "")  # 开头替换
str_ind = str_ind[:-2]  # 结尾去除

# 关闭文件
f_us.close()
f_jp.close()
f_ind.close()

# json转换为字典
dict_us = json.loads(str_us)
dict_jp = json.loads(str_jp)
dict_ind = json.loads(str_ind)

# 获取trend key
dict_us_trend = dict_us.get("data")[0].get("trend")
dict_jp_trend = dict_jp.get("data")[0].get("trend")
dict_ind_trend = dict_ind.get("data")[0].get("trend")

# 获取日期，作为x数据,取到2020年，到314下标结束
str_us_date = dict_us_trend.get("updateDate")[:314]
str_jp_date = dict_jp_trend.get("updateDate")[:314]
str_ind_date = dict_ind_trend.get("updateDate")[:314]

# 获取确诊数目，作为y数据
str_us_qz = dict_us_trend.get("list")[0]["data"][:314]
str_jp_qz = dict_jp_trend.get("list")[0]["data"][:314]
str_ind_qz = dict_ind_trend.get("list")[0]["data"][:314]

# 创建一个折线图对象
line = Line()

# 生成x,y数据
line.add_xaxis(str_us_date)
line.add_yaxis("美国确诊病例数", str_us_qz, label_opts=LabelOpts(is_show=False), itemstyle_opts=ItemStyleOpts(color="red"),
               linestyle_opts=LineStyleOpts(color="red"))
line.add_yaxis("日本确诊病例数", str_jp_qz, label_opts=LabelOpts(is_show=False), itemstyle_opts=ItemStyleOpts(color="blue"),
               linestyle_opts=LineStyleOpts(color="blue"))
line.add_yaxis("印度确诊病例数", str_ind_qz, label_opts=LabelOpts(is_show=False), itemstyle_opts=ItemStyleOpts(color="green"),
               linestyle_opts=LineStyleOpts(color="green"))

# 设置全局配置项
line.set_global_opts(
    title_opts=TitleOpts(title="新冠确诊", pos_left="center", pos_bottom='1%'),  # 标题设置
    legend_opts=LegendOpts(is_show=True),  # 图例是否展示
    toolbox_opts=ToolboxOpts(is_show=True),  # 工具箱是否展示
    visualmap_opts=VisualMapOpts(is_show=True)  # 视觉映射是否展示
)

# 将代码生成图像
line.render("GDP走势折线图.html")
